const MEI_TUAN_DOMAIN = "eb.meituan.com";
const MEI_TUAN_DOMAIN_2 = "ebooking.meituan.com";
const MEI_TUAN_DOMAIN_3 = "me.meituan.com";
const CTRIP_DOMAIN = "ebooking.ctrip.com";
const MFB_DOMAIN = "manfangbao.com";
const XZL_DOMAIN = "xzlpms.com";
const PULL_MEI_TUAN_CANCELED = "pullMeiTuanCanceled";
const PULL_MEI_TUAN_AWAIT_CHECKIN = "pullMeiTuanAwaitCheckin";
const PULL_CTRIP = "pullCtrip";
const PMS_PULL_MEI_TUAN_CANCELED = "pmsPullMeiTuanCanceled";
const PMS_PULL_MEI_TUAN_AWAIT_CHECKIN = "pmsPullMeiTuanAwaitCheckin";
const PMS_PULL_CTRIP = "pmsPullCtrip";
const REFRESH_ORDER_LIST = "refreshOrderList";
const SYNCED_ORDER_ID_CACHE_KEY = 'syncedOrderId'
const CACHE_DURATION_FOR_SYNCED_ORDER_ID = 1000 * 60 * 60 * 24 * 7
async function sleep(timeout) {
  return new Promise((resolve) => setTimeout(resolve, timeout));
}

function insertScript(path) {
  const script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.async = false
  script.src = chrome.runtime.getURL(path);
  document.head.appendChild(script);
}

const devXzlSyncUrl = "https://api-dev.xzlpms.com/order/ota/syncOrder";
const prodXzlSyncUrl = "https://api.xzlpms.com/order/ota/syncOrder";
const devMfbSyncUrl = "https://api-dev.manfangbao.com/order/ota/syncOrder";
const prodMfbSyncUrl = "https://api.manfangbao.com/order/ota/syncOrder";

// 推送数据给 pms 后台
async function pushDataToPms({ ota, content }) {
  let token = localStorage["token"];
  let orderId ="";
  let status="" ;
  console.log("enter pushDataToPms ota is",ota)
  if(ota==='trip'){
    console.log("enter pushDataToPms orderId is",content.OrderID,content.orderType)
    orderId = content.OrderID;
    status = content.orderType;
  }
  else if (ota==='meiTuan'){
    console.log("enter pushDataToPms orderId is",content.orderId,content.status)
    orderId = content.orderId;
    status = content.status;
  }
  // 获取用户token
  if (!token) {
    console.log("token 不存在");
    return;
  }
  const objStr = localStorage.getItem(SYNCED_ORDER_ID_CACHE_KEY)
  let syncOrderIds = []

  if (objStr) {
    const { orderIds = [] } = JSON.parse(objStr)
    syncOrderIds = orderIds
  }
  if (syncOrderIds.includes(orderId+'_'+status)) {
    console.log('已同步过：', orderId,status)
    return;
  }

  token = token.replaceAll('"', "");
  let url = "";
  const host = window.location.host;

  if ([MFB_DOMAIN, XZL_DOMAIN, "localhost"].some((t) => host.includes(t))) {
    if (host.includes("dev") || host.includes("localhost")) {
      if (host.includes(XZL_DOMAIN)) {
        url = devXzlSyncUrl;
      } else {
        url = devMfbSyncUrl;
      }
    } else if (host.includes("www")) {
      if (host.includes(XZL_DOMAIN)) {
        url = prodXzlSyncUrl;
      } else {
        url = prodMfbSyncUrl;
      }
    }
  }

  // 发送请求到pms后台
  let res = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Token: token,
    },
    body: JSON.stringify({
      ota,
      content: JSON.stringify(content),
    }),
  })
    .then((response) => response.json())
    .catch((err) => console.log("Request Failed", err));

  if (res?.code === 0) {
    postMessage({ action: "syncSuccess" }, "*");
    storeSyncedOrder(orderId+"_"+status)
    // await sleep(3000 + Math.random() * 2000)
  }
}

function  storeSyncedOrder  (orderId)  {
  console.log("enter storeSyncedOrder ",orderId)
  try {
    const now = Date.now();
    const { timestamp = 0, orderIds = [] } = JSON.parse(
        localStorage.getItem(SYNCED_ORDER_ID_CACHE_KEY) || '{}'
    )
    const isExpired = now - timestamp > CACHE_DURATION_FOR_SYNCED_ORDER_ID
    const newOrderIds = isExpired ? [orderId] : [...new Set([...orderIds, orderId])]

    if (isExpired || !orderIds.includes(orderId)) {
      localStorage.setItem(
          SYNCED_ORDER_ID_CACHE_KEY,
          JSON.stringify({
            timestamp: isExpired ? now : timestamp,
            orderIds: newOrderIds
          })
      )
    }
  } catch (e) {
    console.error(e)
  }
}
